﻿using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Linq;
using Cubicle.Core.Config;
using Cubicle.Core.Interfaces;
using NLog;

namespace Cubicle.Core.Processors
{
    public class Invoker : ProcessorQueue<object>, IInvoker
    {

        // Nlog
        private static Logger _nlog = LogManager.GetCurrentClassLogger();

        [Import]
        protected CompositionContainer Container;

        public Invoker(CompositionContainer container, ProcessorConfig config)
        {
            Container = container;
            Build(config);
        }

        public Invoker(CompositionContainer container, EngineConfig config, string key)
            : this(container, config.Queues.FirstOrDefault(x => x.Key == key).ProcessorConfig) { }

        public void Build(ProcessorConfig config)
        {
            Build(Container, config);
        }

        public override object Process(object input)
        {
            try
            {
                // Start message execution
                return base.Process(input);
            }
            catch (Exception ex)
            {
                while (ex != null)
                {
                    _nlog.ErrorException("Aborting message execution.", ex);
                    ex = ex.InnerException;
                }
                return null;
            }
        }

    }
}